﻿using System;
using System.Collections.Generic;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting;

namespace Cjc.ExpressionEngine
{
	public class Engine
	{
		private ScriptEngine scriptEngine;
		private Dictionary<SymbolId, Formula> formulas = new Dictionary<SymbolId,Formula>();

		public Engine()
		{
			scriptEngine = Hosting.Excel.CreateEngine();
		}

		public Engine( ScriptEngine scriptEngine )
		{
			this.scriptEngine = scriptEngine;
		}

		internal ScriptEngine ScriptEngine { get { return scriptEngine; } }

		public bool ContainsKey( string key )
		{
			return ContainsSymbol( SymbolTable.StringToCaseInsensitiveId( key ) );
		}

		internal bool ContainsSymbol( SymbolId symbol )
		{
			lock ( formulas )
			{
				return formulas.ContainsKey( symbol );
			}
		}

		public Formula this[ string key ]
		{
			get { return this[ SymbolTable.StringToCaseInsensitiveId( key ) ]; }
		}

		internal Formula this[ SymbolId symbol ]
		{
			get
			{
				lock ( formulas )
				{
					return formulas.ContainsKey( symbol )
						? formulas[ symbol ]
						: formulas[ symbol ] = new Formula( this );
				}
			}

			set
			{
				lock ( formulas )
				{
					formulas[ symbol ] = value;
				}
			}
		}
	}
}